package com.apes.fn.scm.internal.help.model;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @BelongsProject: apes
 * @BelongsPackage: com.apes.fn.scm.retailReturn
 * @ClassName: InternalHelpReturnApproval
 * @Author: pyb
 * @CreateTime: 2020-06-02 15:35
 * @Description: 內协退货
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = InternalHelpReturnApproval.CONST_TABLE_NAME)
public class InternalHelpReturnApproval extends Model {
    public static final String CONST_TABLE_NAME = "internal_help_return";
    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "內协退货申请审批单", prefix = "NT%(company)%(yy)%(month)", padding = 4, useDateRange=true)
    private String id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "order_company_id", referencedColumnName = "id")
    @Comment("对方公司")
    private PartyRole orderCompany;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门")
    private Dept dept;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @Transient
    private Map customerCar;


    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer()
        );
    }

    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ship_location_id", referencedColumnName = "id")
    @Comment("发货仓库")
    private Location shipLocation;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_location_id", referencedColumnName = "id")
    @Comment("收货仓库")
    private Location receiptLocation;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    @Comment("返厂原因")
    private Enumeration returnReason;


    @Column(name = "state", length = 10, nullable = false)
    @States(name = "订单状态", values = {
            @State(id = "sent", name = "新建"),
            @State(id = "approve", name = "审核"),
            @State(id = "apply", name = "申请"),
            @State(id = "reject", name = "驳回"),
            @State(id = "done", name = "已完成"),
            @State(id = "receipt", name = "已收货"),
            @State(id = "delivered", name = "待发货"),
            @State(id = "ship", name = "已发货")})
    private String state;


    @Column(name = "cross_system", length = 36)
    @States(name = "跨系统", values = {
            @State(id = "erp", name = "老系统"),
            @State(id = "unidentified", name = "未鉴定"),
            @State(id = "esb", name = "新系统")})
    private String crossSystem;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date dateApprove;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_uid", referencedColumnName = "id")
    @Comment("申请人")
    private PartyRole applyUid;

    @Column(name = "date_apply")
    @Comment("申请日期")
    private Date dateApply;

    @Column(name = "note")
    @Comment("备注")
    private String note;

    @Column(name = "process_initiator")
    @Comment("流程发起人")
    private String processInitiator;

    @Column(name = "process_initiating_department")
    @Comment("流程发起人部门")
    private String processInitiatingDepartment;

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtUntaxed = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;


    @Column(name = "origin", length = 30)
    @Comment("源单号")
    private String origin;

    @Column(name = "origin_business_type", length = 32, nullable = true)
    @Comment("源单类型")
    private String originBusinessType;

    @Column(name = "source", length = 30)
    @Comment("来源单号")
    private String source;

    @Column(name = "source_business_type", length = 32, nullable = true)
    @Comment("来源单类型")
    private String sourceBusinessType;


    @OneToMany(mappedBy = "approval", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<InternalHelpReturnApprovalItem> approvalItems = new HashSet<>();

    
    public Set<InternalHelpReturnApprovalItem> getApprovalItems() {
        for (InternalHelpReturnApprovalItem approvalItem : approvalItems) {
            approvalItem.setApproval(this);
            approvalItem.setCompany(company);

        }
        return approvalItems;
    }

    @Transient
    private String candidates;

    public void computeAmt() {
        amtUntaxed = 0; amtTax = 0;
        for (InternalHelpReturnApprovalItem item : approvalItems) {
            item.computeAmt();
            amtUntaxed += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
        }
        amtTotal = amtUntaxed + amtTax;
    }


    @Transient
    private PartyRole orderCustomer;

    public PartyRole getOrderCustomer() {
        if (orderCompany==null||orderCompany.getParty()==null)return null;
        orderCustomer =  orderCompany.getParty().getPatyRoleByType("Customer");
        return orderCustomer;
    }
}
